import { Router, Request, Response } from 'express';
import { ConnectionService } from '../services/ConnectionService';
import { dorisConnectionManager } from '../database/connectors/DorisConnectionManager';
import Joi from 'joi';

const router = Router();
const connectionService = new ConnectionService();

// 验证中间件
const validateConnection = (req: Request, res: Response, next: any): void => {
  const schema = Joi.object({
    name: Joi.string().min(1).max(255).required(),
    host: Joi.string().min(1).max(255).required(),
    port: Joi.number().integer().min(1).max(65535).required(),
    username: Joi.string().min(1).max(255).required(),
    password: Joi.string().min(6).required(),
    database_name: Joi.string().max(255).optional(),
    ssl_enabled: Joi.boolean().optional(),
    timeout: Joi.number().integer().min(1000).max(300000).optional(),
    max_connections: Joi.number().integer().min(1).max(100).optional(),
    connection_params: Joi.object().optional(),
    created_by: Joi.string().max(255).optional()
  });

  const { error } = schema.validate(req.body);
  if (error) {
    res.status(400).json({
      success: false,
      message: '请求参数验证失败',
      errors: error.details.map(detail => detail.message)
    });
    return;
  }

  next();
};

const validateConnectionUpdate = (req: Request, res: Response, next: any): void => {
  const schema = Joi.object({
    name: Joi.string().min(1).max(255).optional(),
    host: Joi.string().min(1).max(255).optional(),
    port: Joi.number().integer().min(1).max(65535).optional(),
    username: Joi.string().min(1).max(255).optional(),
    password: Joi.string().min(6).optional(),
    database_name: Joi.string().max(255).optional(),
    ssl_enabled: Joi.boolean().optional(),
    timeout: Joi.number().integer().min(1000).max(300000).optional(),
    max_connections: Joi.number().integer().min(1).max(100).optional(),
    connection_params: Joi.object().optional()
  });

  const { error } = schema.validate(req.body);
  if (error) {
    res.status(400).json({
      success: false,
      message: '请求参数验证失败',
      errors: error.details.map(detail => detail.message)
    });
    return;
  }

  next();
};

// 创建连接
router.post('/', validateConnection, async (req: Request, res: Response) => {
  try {
    const connection = await connectionService.createConnection(req.body);
    
    res.status(201).json({
      success: true,
      message: '连接创建成功',
      data: connection
    });
  } catch (error: any) {
    res.status(400).json({
      success: false,
      message: error.message || '创建连接失败'
    });
  }
});

// 获取连接列表
router.get('/', async (req: Request, res: Response) => {
  try {
    const options: {
      active_only?: boolean;
      created_by?: string;
      limit?: number;
      offset?: number;
    } = {};
    
    if (req.query.active_only === 'true') {
      options.active_only = true;
    }
    
    if (req.query.created_by) {
      options.created_by = req.query.created_by as string;
    }
    
    if (req.query.limit) {
      options.limit = parseInt(req.query.limit as string);
    }
    
    if (req.query.offset) {
      options.offset = parseInt(req.query.offset as string);
    }

    const result = await connectionService.getConnections(options);
    
    res.json({
      success: true,
      data: result
    });
  } catch (error: any) {
    res.status(500).json({
      success: false,
      message: error.message || '获取连接列表失败'
    });
  }
});

// 获取单个连接详情
router.get('/:id', async (req: Request, res: Response): Promise<void> => {
  try {
    const connection = await connectionService.getConnection(req.params.id);
    
    if (!connection) {
      res.status(404).json({
        success: false,
        message: '连接不存在'
      });
      return;
    }
    
    res.json({
      success: true,
      data: connection
    });
  } catch (error: any) {
    res.status(500).json({
      success: false,
      message: error.message || '获取连接详情失败'
    });
  }
});

// 更新连接
router.put('/:id', validateConnectionUpdate, async (req: Request, res: Response) => {
  try {
    const connection = await connectionService.updateConnection(req.params.id, req.body);
    
    // 重新加载连接配置
    await dorisConnectionManager.reloadConnection(req.params.id);
    
    res.json({
      success: true,
      message: '连接更新成功',
      data: connection
    });
  } catch (error: any) {
    res.status(400).json({
      success: false,
      message: error.message || '更新连接失败'
    });
  }
});

// 删除连接
router.delete('/:id', async (req: Request, res: Response): Promise<void> => {
  try {
    // 先关闭连接池
    await dorisConnectionManager.closeConnection(req.params.id);
    
    const success = await connectionService.deleteConnection(req.params.id);
    
    if (!success) {
      res.status(404).json({
        success: false,
        message: '连接不存在'
      });
      return;
    }
    
    res.json({
      success: true,
      message: '连接删除成功'
    });
  } catch (error: any) {
    res.status(400).json({
      success: false,
      message: error.message || '删除连接失败'
    });
  }
});

// 测试连接
router.post('/:id/test', async (req: Request, res: Response) => {
  try {
    const testResult = await dorisConnectionManager.testConnection(req.params.id);
    
    res.json({
      success: true,
      data: testResult
    });
  } catch (error: any) {
    res.status(500).json({
      success: false,
      message: error.message || '测试连接失败'
    });
  }
});

// 获取数据库列表
router.get('/:id/databases', async (req: Request, res: Response) => {
  try {
    const databases = await dorisConnectionManager.getDatabases(req.params.id);
    
    res.json({
      success: true,
      data: databases
    });
  } catch (error: any) {
    res.status(500).json({
      success: false,
      message: error.message || '获取数据库列表失败'
    });
  }
});

// 获取表列表
router.get('/:id/tables', async (req: Request, res: Response) => {
  try {
    const database = req.query.database as string;
    const tables = await dorisConnectionManager.getTables(req.params.id, database);
    
    res.json({
      success: true,
      data: tables
    });
  } catch (error: any) {
    res.status(500).json({
      success: false,
      message: error.message || '获取表列表失败'
    });
  }
});

// 获取表结构
router.get('/:id/tables/:tableName/schema', async (req: Request, res: Response) => {
  try {
    const database = req.query.database as string;
    const schema = await dorisConnectionManager.getTableSchema(
      req.params.id, 
      req.params.tableName, 
      database
    );
    
    res.json({
      success: true,
      data: schema
    });
  } catch (error: any) {
    res.status(500).json({
      success: false,
      message: error.message || '获取表结构失败'
    });
  }
});

// 获取数据库完整结构
router.get('/:id/schema', async (req: Request, res: Response) => {
  try {
    const database = req.query.database as string;
    const schema = await dorisConnectionManager.getDatabaseSchema(req.params.id, database);
    
    res.json({
      success: true,
      data: schema
    });
  } catch (error: any) {
    res.status(500).json({
      success: false,
      message: error.message || '获取数据库结构失败'
    });
  }
});

// 激活/停用连接
router.patch('/:id/toggle', async (req: Request, res: Response): Promise<void> => {
  try {
    const { is_active } = req.body;
    
    if (typeof is_active !== 'boolean') {
      res.status(400).json({
        success: false,
        message: 'is_active参数必须是布尔值'
      });
      return;
    }
    
    // 如果要停用连接，先关闭连接池
    if (!is_active) {
      await dorisConnectionManager.closeConnection(req.params.id);
    }
    
    const connection = await connectionService.toggleConnectionStatus(req.params.id, is_active);
    
    res.json({
      success: true,
      message: is_active ? '连接已激活' : '连接已停用',
      data: connection
    });
  } catch (error: any) {
    res.status(400).json({
      success: false,
      message: error.message || '切换连接状态失败'
    });
  }
});

// 获取连接统计信息
router.get('/:id/stats', async (req: Request, res: Response) => {
  try {
    const stats = await connectionService.getConnectionStats(req.params.id);
    
    res.json({
      success: true,
      data: stats
    });
  } catch (error: any) {
    res.status(500).json({
      success: false,
      message: error.message || '获取连接统计失败'
    });
  }
});

// 批量测试连接
router.post('/test-multiple', async (req: Request, res: Response): Promise<void> => {
  try {
    const { connection_ids } = req.body;
    
    if (!Array.isArray(connection_ids)) {
      res.status(400).json({
        success: false,
        message: 'connection_ids必须是数组'
      });
      return;
    }
    
    const results = await dorisConnectionManager.testMultipleConnections(connection_ids);
    
    res.json({
      success: true,
      data: results
    });
  } catch (error: any) {
    res.status(500).json({
      success: false,
      message: error.message || '批量测试连接失败'
    });
  }
});

// 获取连接健康状态
router.get('/health/summary', async (_req: Request, res: Response): Promise<void> => {
  try {
    const healthSummary = await dorisConnectionManager.getHealthSummary();
    
    res.json({
      success: true,
      data: healthSummary
    });
  } catch (error: any) {
    res.status(500).json({
      success: false,
      message: error.message || '获取健康状态失败'
    });
  }
});

// 获取所有连接池状态
router.get('/pools/status', async (_req: Request, res: Response): Promise<void> => {
  try {
    const poolStats = await dorisConnectionManager.getAllConnectionStats();
    
    res.json({
      success: true,
      data: poolStats
    });
  } catch (error: any) {
    res.status(500).json({
      success: false,
      message: error.message || '获取连接池状态失败'
    });
  }
});

// 更新连接密码
router.patch('/:id/password', async (req: Request, res: Response): Promise<void> => {
  try {
    const { password } = req.body;
    
    if (!password || typeof password !== 'string' || password.length < 6) {
      res.status(400).json({
        success: false,
        message: '密码长度不能少于6位'
      });
      return;
    }
    
    const success = await connectionService.updateConnectionPassword(req.params.id, password);
    
    if (!success) {
      res.status(404).json({
        success: false,
        message: '连接不存在'
      });
      return;
    }
    
    // 重新加载连接配置
    await dorisConnectionManager.reloadConnection(req.params.id);
    
    res.json({
      success: true,
      message: '密码更新成功'
    });
  } catch (error: any) {
    res.status(400).json({
      success: false,
      message: error.message || '更新密码失败'
    });
  }
});

// 执行SQL查询（用于测试连接功能）
router.post('/:id/query', async (req: Request, res: Response): Promise<void> => {
  try {
    const { sql, params = [] } = req.body;
    
    if (!sql || typeof sql !== 'string') {
      res.status(400).json({
        success: false,
        message: 'SQL语句不能为空'
      });
      return;
    }
    
    // 限制查询类型，只允许SELECT语句用于测试
    const trimmedSql = sql.trim().toUpperCase();
    if (!trimmedSql.startsWith('SELECT') && !trimmedSql.startsWith('SHOW') && !trimmedSql.startsWith('DESCRIBE')) {
      res.status(400).json({
        success: false,
        message: '只允许执行SELECT、SHOW、DESCRIBE语句'
      });
      return;
    }
    
    const result = await dorisConnectionManager.executeQuery(req.params.id, sql, params);
    
    res.json({
      success: true,
      data: result
    });
  } catch (error: any) {
    res.status(500).json({
      success: false,
      message: error.message || '查询执行失败'
    });
  }
});

export default router;